package com.sxhalo.fsms.controller.api;

import com.sxhalo.fsms.controller.BaseController;
import com.sxhalo.fsms.domain.*;
import com.sxhalo.fsms.export.ExcelUtils;
import com.sxhalo.fsms.export.ExportExcelUtils;
import com.sxhalo.fsms.export.ExportSetInfo;
import com.sxhalo.fsms.log.SysControllerLog;
import com.sxhalo.fsms.service.*;
import com.sxhalo.fsms.util.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.text.DecimalFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.temporal.TemporalAdjusters;
import java.util.*;

@Controller
@RequestMapping("/api")
public class EnergyAnalysisController extends BaseController {

	@Autowired
	private IDeviceSmartRunningDataService runningDataService;
    @Autowired
    private IDeviceEmRunningDataService emrunningDataService;
    @Autowired
    private IFactAreaService areaService;

    @Autowired
    private ISysSettingsService settingsService;
    @Autowired
    private IUserInfoService userService;
    @Autowired
    private IFactDeviceService deviceService;


	@ResponseBody
	@RequestMapping(value = "/energy/analysis", method = RequestMethod.GET, produces="application/json;charset=UTF-8")
	public ApiResult findEnergyAnalysis(HttpServletRequest req,Integer typeId,Integer deviceId,Integer areaId) {
     	//图标数据
        String where=getWhere(deviceId,areaId);
	    List<Map<String,Object>> phaseHis=emrunningDataService.getEnergyPhaseHis(where);
        LocalDateTime time = LocalDateTime.of(LocalDate.from(LocalDateTime.now().with(LocalDate.now().minusDays(1))), LocalTime.MIN);
        String[] phaseTime = new String[48];
		Float[] yestodayNum = new Float[48];
        Float[] todayNum = new Float[48];
        Map<String,Float> phaseHisMap=new HashMap<String,Float>();
        for( Map<String,Object> map:phaseHis){
          phaseHisMap.put(map.get("time").toString(),new Float(map.get("value")==null?"0":map.get("value").toString()));
        }
        Map<String,Object> returnDate=new HashMap<String,Object>();
        Map<String,Object> peakValue=new HashMap<String,Object>();
		 //封装图标数据

        getChartData(time,phaseTime ,yestodayNum , phaseHisMap,peakValue,"yestoday");
        time = LocalDateTime.of(LocalDate.now(), LocalTime.MIN);
        getChartData(  time,phaseTime ,todayNum , phaseHisMap,peakValue,"today");
        returnDate.put("peakValue",peakValue);
        returnDate.put("phaseTime",phaseTime);
        returnDate.put("yestodayNum",yestodayNum);
        returnDate.put("todayNum",todayNum);
		return ApiResult.retOK(req,returnDate);
	}




    @ResponseBody
    @RequestMapping(value = "/energy/analysis/energyNum", method = RequestMethod.GET, produces="application/json;charset=UTF-8")
    public ApiResult findEnergyNum(HttpServletRequest req,Integer deviceId,Integer areaId) {
        //图标数据
        String where=getWhere(deviceId,areaId);
        //环比数据
        Map<String,Object>  energyNum=runningDataService.getEnergyNumStatistics(where);
        Map<String,Object>  nenergyNum=new HashMap<>();
        nenergyNum.putAll(new HashMap<>());
        if(energyNum==null){
            energyNum=new HashMap<>();
        }
        Object yestodayNum=energyNum.get("yestoday_num");
        Object lastMouthNum=energyNum.get("last_mouth_num");
        Object lastYearNum=energyNum.get("last_year_num");
        energyNum.put("today_num",subtract(yestodayNum,energyNum.get("today_num")));
        energyNum.put("current_mouth_num",subtract(lastMouthNum,energyNum.get("current_mouth_num")));
        energyNum.put("this_year_num",subtract(lastYearNum,energyNum.get("this_year_num")));
        energyNum.put("yestoday_num",subtract(energyNum.get("before_yestoday_num"),yestodayNum));
        energyNum.put("last_mouth_num",subtract(energyNum.get("before_last_month_num"),lastMouthNum));
        energyNum.put("last_year_num",subtract(energyNum.get("before_last_year_num"),lastYearNum));

        CacheUtil.putObject("energyNum",nenergyNum);
        return ApiResult.retOK(req,energyNum);
    }


    @ResponseBody
	@RequestMapping(value = "/energy/analysisByType", method = RequestMethod.GET, produces="application/json;charset=UTF-8")
	public ApiResult findEnergyAnalysisByType(Integer typeId,HttpServletRequest req,Integer deviceId,Integer areaId) {
        Map<String,Object> returnDate=new HashMap<String,Object>();
        String where=getWhere(deviceId,areaId);
        findAlarmAnalysisByType(typeId,returnDate,where);
		return ApiResult.retOK(req,returnDate);
	}

    @ResponseBody
    @RequestMapping(value = "/energy/reportByArea", method = RequestMethod.GET, produces="application/json;charset=UTF-8")
    public ApiResult reportByArea(String type,String date, HttpServletRequest req,Integer deviceId,Integer areaId) {

        List<Map<String,Object>> phaseHis=null;
         try{
             List<FactArea> areaList=areaService.findWhereList(" use_state=1 and delete_flag=0 and parent_id=0 "," area_id");
             String where=getReportWhere(type,date);
             String where1=getReportWhere1(type,date);
             Map<String,Object> lastdata=  emrunningDataService.getLastData(areaList,getLastWhere(date));
             phaseHis=emrunningDataService.getEnergyReport(areaList,where,where1,type);
             getreportdatas(areaList,phaseHis,type,lastdata);


         }catch(Exception e ){
             System.out.println(e);
         }finally {
             return ApiResult.retOK(req,phaseHis);
         }
    }


    @ResponseBody
    @RequestMapping(value = "/energy/reportByDevice", method = RequestMethod.GET, produces="application/json;charset=UTF-8")
    public ApiResult reportByDevice(String type,String date, HttpServletRequest req,Integer deviceId,Integer areaId) {
        Map<String,Object> returnDate=new HashMap<String,Object>();
        List<Map<String,Object>> phaseHis=null;
        try{
            List<FactDevice> deviceList=deviceService.getTypeList(" device_type_id=3 and use_state=1 and delete_flag=0");
            String where=getReportWhere(type,date);
            String where1=getReportWhere1(type,date);

            Map<String,Object> lastdata=  emrunningDataService.getLastData1(deviceList,getLastWhere(date));
            phaseHis=emrunningDataService.getEnergyReport1(deviceList,where,where1,type);
            getreport1datas(deviceList,phaseHis,type,lastdata);

        }catch(Exception e){
            System.out.println(e);
        }finally {
            return ApiResult.retOK(req,phaseHis);
        }
    }


    @ResponseBody
    @RequestMapping(value = "/energy/arealistAndSet", method = RequestMethod.GET, produces = "application/json;charset=UTF-8")
    public ApiResult arealistAndSet(Integer current, Integer parentId, Integer pageSize, HttpServletRequest req) {
        String where = "a.delete_flag=0 and a.parent_id=0";
        String order = " parent_id asc,area_id asc";
        Map<String,Object> returnDate=new HashMap<String,Object>();
        SysSettings set=settingsService.selectByPrimaryKey("multiplier");
        SysSettings conversion=settingsService.selectByPrimaryKey("conversion_index");
        List<FactArea> list = areaService.findWhereList(where, order);
        returnDate.put("multiplier",set==null?4000:set.getValue());
        returnDate.put("conversion",conversion==null?0.1229:conversion.getValue());
        returnDate.put("list",list);
        return ApiResult.retOK(req, returnDate);

    }

    @ResponseBody
    @RequestMapping(value = "/energy/devicelistAndSet", method = RequestMethod.GET, produces = "application/json;charset=UTF-8")
    public ApiResult devicelistAndSet(Integer current, Integer parentId, Integer pageSize, HttpServletRequest req) {
        String where = "a.delete_flag=0 and a.use_state=1 and device_type_id=3";
        String order = " create_time desc";
        Map<String,Object> returnDate=new HashMap<String,Object>();
        SysSettings set=settingsService.selectByPrimaryKey("multiplier");
        SysSettings conversion=settingsService.selectByPrimaryKey("conversion_index");
        List<FactDevice> list = deviceService.findWhereList(where, order);
        returnDate.put("multiplier",set==null?4000:set.getValue());
        returnDate.put("conversion",conversion==null?0.1229:conversion.getValue());
        returnDate.put("list",list);
        return ApiResult.retOK(req, returnDate);

    }



    @ResponseBody
    @RequestMapping(value = "/energy/unitReport", method = RequestMethod.GET, produces="application/json;charset=UTF-8")
    public ApiResult findEnergyAnalysisByType(String type,String sdate,String edate,HttpServletRequest req,Integer deviceId) throws ParseException {


        List<Map<String,Object>>  returnDate= formateUnitReportData( type, sdate, edate,deviceId);

        return ApiResult.retOK(req,returnDate);
    }

    private  List<Map<String,Object>> formateUnitReportData(String type,String sdate,String edate,Integer deviceId) throws ParseException {
        Map<String,Object> returnDate=new HashMap<String,Object>();
        String where1=getUnitWhere1(type,deviceId,sdate,edate);
        String where2=getUnitWhere2(type,deviceId,sdate,edate);
        List<Map<String,Object>> phaseHis=emrunningDataService.getUnitEnergyReport(where1,where2);

        String  sdate1=   DateUtil.addInteger(sdate,2,-2);
        List<Map<String,Object>> newPhaseHis=new ArrayList<>();
        formatEnergData(sdate1,edate,phaseHis,newPhaseHis);

        List<Map<String,Object>> newPhaseHis1=new ArrayList<>();
        String sdate2=   DateUtil.addInteger(sdate,1,-1);
        sdate2=   DateUtil.addInteger(sdate2,2,-1);
        String edate2=   DateUtil.addInteger(edate,1,-1);
        formatEnergData(sdate2,edate2,phaseHis,newPhaseHis1);
        Map<String,Object> huanbiLastMap=newPhaseHis.get(0);
        Map<String,Object> tongbiLastMap=newPhaseHis1.get(0);
        Map<String,Object> lastMap=newPhaseHis.get(1);
        newPhaseHis.remove(0);
        newPhaseHis.remove(0);
        newPhaseHis1.remove(0);

        List<Map<String,Object>> newPhaseHis2=new ArrayList<>();
        Map<String,Object> map;
        for(int i=0;i<newPhaseHis.size();i++){
            Object date= subtract(lastMap.get("total_active_energy"),newPhaseHis.get(i).get("total_active_energy"));
            Object date1= subtract(huanbiLastMap.get("total_active_energy"),lastMap.get("total_active_energy"));
            Object date2= subtract(tongbiLastMap.get("total_active_energy"),newPhaseHis1.get(i).get("total_active_energy"));

            map=new HashMap<>();
            map.put("time",newPhaseHis.get(i).get("acquisition_time"));
            map.put("value",date);
            map.put("ttime",newPhaseHis1.get(i).get("acquisition_time"));
            map.put("tvalue",date2);
            map.put("tdecrement",subtract1(date,date2));
            map.put("tGrowthRate",formatGrowthrate(date,date2));
            map.put("htime",lastMap.get("acquisition_time"));
            map.put("hvalue",date1);
            map.put("hdecrement",subtract1(date,date1));
            map.put("hGrowthRate",formatGrowthrate(date,date1));
            newPhaseHis2.add(map);
            tongbiLastMap=lastMap;
            lastMap=newPhaseHis.get(i);
            huanbiLastMap=newPhaseHis1.get(i);
        }
        return  newPhaseHis2;
    }

    private void formatEnergData(String data,String edate, List<Map<String,Object>> phaseHis,List<Map<String,Object>> newPhaseHis) throws ParseException {
        Boolean isExits=false;
        for( Map<String,Object>  map:phaseHis){
            if(map.get("acquisition_time").equals(data)){
                isExits=true;
                newPhaseHis.add(map);
                break ;
            }
        }
        if(!isExits){
            Map<String,Object>  map=new HashMap<>();
            map.put("acquisition_time",data);
            map.put("total_active_energy",0.00);
            newPhaseHis.add(map);
        }

        if(DateUtil.sdf2.parse(edate).compareTo(DateUtil.sdf2.parse(data))>0){
            data=   DateUtil.addInteger(data,2,1);
            formatEnergData(data,edate,phaseHis,newPhaseHis);


        }

    }



    private String getUnitWhere1(String type,Integer deviceId,String date1,String date2){
        String where=" device_id= "+deviceId;
        String datas=   DateUtil.addInteger(date1,2,-2);
        where+="  and  DATE_FORMAT(acquisition_time,'%Y-%m') >='"+datas +"' and  DATE_FORMAT(acquisition_time,'%Y-%m')<='"+date2+"'";

        return  where;
    }


    private String getUnitWhere2(String type,Integer deviceId,String date1,String date2){
        String where=" device_id= "+deviceId;
        String datas=   DateUtil.addInteger(date1,1,-1);
        datas=   DateUtil.addInteger(datas,2,-1);
        String datas1=   DateUtil.addInteger(date2,1,-1);
        where+="  and  DATE_FORMAT(acquisition_time,'%Y-%m') >='"+datas +"' and  DATE_FORMAT(acquisition_time,'%Y-%m')<='"+datas1+"'";

        return  where;
    }

    @ResponseBody
    @SysControllerLog(operationName = "导出", modelName = "单品能耗")
    @RequestMapping(value = "/energy/unitReport/export", method = RequestMethod.GET)
    public void unitReportDownload(String type,String sdate,String edate,Integer deviceId,String deviceName, HttpServletRequest request, HttpServletResponse response)
    {

        try{

            String token = CookieUtils.getCookieValue(request, "token");
            if (token != null) {
                Integer userId = TokenUtil.getUserId(token);
                UserInfo record = userService.selectByPrimaryKey(userId);

                ByteArrayOutputStream os = new ByteArrayOutputStream();
                deviceName=deviceName.replaceAll("@","#");
                String fileName =deviceName+"-"+sdate+"~"+edate+ "单品能耗报表";
                List<Map<String,Object>>  returnDate= formateUnitReportData( type, sdate, edate,deviceId);
                String[] Userkeys = {  "time", "value", "ttime","tvalue",
                        "tdecrement", "tGrowthRate", "htime", "hvalue", "hdecrement","hGrowthRate"};
                ExportSetInfo info = new ExportSetInfo();
                info.setHeadNames(createExcelHead2( ));
                info.setUserName(record.getRealName());
                info.setDatalist(returnDate);
                info.setTitles(fileName);
                info.setFieldNames(Userkeys);
                info.setOut(os);
                ExportExcelUtils.export2Excel(info);
                ExportExcelUtils.ExcelDownload(fileName, response, os);
            }
        }catch (Exception e){
            System.out.println(e);
        }finally {

        }

    }


//
    @ResponseBody
    @SysControllerLog(operationName = "导出", modelName = "能耗报表")
    @RequestMapping(value = "/energy/reportByArea/export", method = RequestMethod.GET)
    public void reportByAreaDownload(String type,String date, HttpServletRequest request, HttpServletResponse response) {
            try{
                String token = CookieUtils.getCookieValue(request, "token");
                if (token != null) {
                    Integer userId = TokenUtil.getUserId(token);
                    UserInfo record = userService.selectByPrimaryKey(userId);
                    ByteArrayOutputStream os = new ByteArrayOutputStream();
                    String fileName =getTableName(type, date) ;
                    String where=getReportWhere(type,date);
                    String where1=getReportWhere1(type,date);
                    List<FactArea> areas= areaService.findWhereList(" delete_flag=0 and parent_id=0 ","area_id ");
                    String[] Userkeys = createUserKey1(areas);
                    List<Map<String,Object>> phaseHis=emrunningDataService.getEnergyReport(areas,where,where1,type);
                    Map<String,Object> lastdata=  emrunningDataService.getLastData(areas,getLastWhere(date));
                    String section=  getDatasection(type,date);
                    ExportSetInfo info = new ExportSetInfo();
                    info.setHeadNames(createExcelHead( areas));
                    getreportdatas(areas,phaseHis,type,lastdata);
                    info.setDatalist(phaseHis);
                    info.setTitles(fileName);
                    info.setDateSection(section);
                    info.setUserName(record.getRealName());
                    info.setFieldNames(Userkeys);
                    info.setOut(os);
                    ExportExcelUtils.export2Excel(info);
                    ExportExcelUtils.ExcelDownload(fileName, response, os);
                }
            }catch (Exception e){
                System.out.println(e);
            }finally {

            }

    }


    private String getTableName (String type,String date) throws ParseException{
        String fileName = "能耗报表";
        if(type.equals("year")) {
            int quarter =   DateUtil.getQuarterStartByDate(date);
            fileName=date.substring(0,4)+"年"+fileName;
        }else  if(type.equals("quarter")) {
            int quarter =   DateUtil.getQuarterStartByDate(date);
            fileName=date.substring(0,4)+"年"+   (quarter/3 +1)+"季度" +fileName;
        }else  if(type.equals("week")) {
            fileName= DateUtil.getWeekOfYear(date)+fileName;
        }else  if(type.equals("month")) {
            fileName=  DateUtil.sdf11.format(DateUtil.sdf5.parse(date)) +fileName;
        }else{
            fileName=DateUtil.sdf10.format(DateUtil.sdf5.parse(date)) +fileName;
        }
        return  fileName;
    }

    @ResponseBody
    @SysControllerLog(operationName = "导出", modelName = "能耗报表")
    @RequestMapping(value = "/energy/reportByDevice/export", method = RequestMethod.GET)
    public void reportByDeviceDownload(String type,String date, HttpServletRequest request, HttpServletResponse response)
    {
        try{
            String token = CookieUtils.getCookieValue(request, "token");
            if (token != null) {
                String section=  getDatasection(type,date);
                Integer userId = TokenUtil.getUserId(token);
                UserInfo record = userService.selectByPrimaryKey(userId);
                ByteArrayOutputStream os = new ByteArrayOutputStream();
                String fileName = getTableName(type, date);
                List<FactDevice> deviceList = deviceService.getTypeList(" device_type_id=3 and use_state=1 and delete_flag=0");
                String[] Userkeys = createUserKey(deviceList);
                String where = getReportWhere(type, date);
                String where1 = getReportWhere1(type, date);
                List<Map<String, Object>> phaseHis = emrunningDataService.getEnergyReport1(deviceList, where, where1, type);
                Map<String, Object> lastdata = emrunningDataService.getLastData1(deviceList, getLastWhere(date));
                ExportSetInfo info = new ExportSetInfo();
                info.setDateSection(section);
                info.setHeadNames(createExcelHead1(deviceList));
                getreport1datas(deviceList, phaseHis, type, lastdata);
                info.setDatalist(phaseHis);
                info.setTitles(fileName);
                info.setFieldNames(Userkeys);
                info.setUserName(record.getRealName());
                info.setOut(os);
                ExportExcelUtils.export2Excel(info);
                ExportExcelUtils.ExcelDownload(fileName, response, os);
            }
        }catch (Exception e){
            System.out.println(e);
        }finally {
        }
    }


    // 表头选择
    private List<String[]> createExcelHead2() {
        List<String[]> headlist = new ArrayList<String[]>();
        String[] row1 = {  "本期", "本期单位能耗", "同比日期", "同比单位能耗", "增减量",  "同比增长率","环比日期", "环比单位能耗", "增减量","环比增长率" };
        headlist.add(row1);
        return headlist;
    }


    // 表头选择
    private List<String[]> createExcelHead(  List<FactArea> areas) {
        List<String[]> headlist = new ArrayList<String[]>();
        String[] row1 = new String[1+areas.size()*3];
        String[] row2= new String[1+areas.size()*3];
        row1[0]="时间";
        row2[0]="时间";
        for ( int i=0;i<areas.size();i++ ){
            row1[i*3+1]=areas.get(i).getAreaName();
            row1[i*3+2]=areas.get(i).getAreaName();
            row1[i*3+3]=areas.get(i).getAreaName();
            row2[i*3+1]= "总电能";
            row2[i*3+2]="有功";
            row2[i*3+3]="无功";
        }
        headlist.add(row1);
        headlist.add(row2);
        return headlist;
    }

    // 表头选择
    private List<String[]> createExcelHead1( List<FactDevice> deviceList) {
        List<String[]> headlist = new ArrayList<String[]>();
        String[] row1 = new String[1+deviceList.size()*4];
        String[] row2= new String[1+deviceList.size()*4];
        row1[0]="时间";
        row2[0]="时间";

        for ( int i=0;i<deviceList.size();i++ ){
            row1[i*4+1]=deviceList.get(i).getDeviceName();
            row1[i*4+2]=deviceList.get(i).getDeviceName();
            row1[i*4+3]=deviceList.get(i).getDeviceName();
            row1[i*4+4]=deviceList.get(i).getDeviceName();
            row2[i*4+1]= "总电能";
            row2[i*4+2]="有功";
            row2[i*4+3]="无功";
            row2[i*4+4]="功率因素";
        }

        headlist.add(row1);
        headlist.add(row2);
        return headlist;
    }





    // 表头选择
    private String[] createUserKey1( List<FactArea> areas) {
        String[] row1 = new String[1+areas.size()*3];
        row1[0]="time";
        for ( int i=0;i<areas.size();i++ ){
            row1[i*3+1]="valuea"+areas.get(i).getAreaId();
            row1[i*3+2]="valueb"+areas.get(i).getAreaId();
            row1[i*3+3]="valuec"+areas.get(i).getAreaId();
        }
        return row1;
    }

    // 表头选择
    private String[] createUserKey( List<FactDevice> deviceList) {
        String[] row1 = new String[1+deviceList.size()*4];
        row1[0]="time";

        for ( int i=0;i<deviceList.size();i++ ){
            row1[i*4+1]="valuea"+deviceList.get(i).getDeviceId();
            row1[i*4+2]="valueb"+deviceList.get(i).getDeviceId();
            row1[i*4+3]="valuec"+deviceList.get(i).getDeviceId();
            row1[i*4+4]="valued"+deviceList.get(i).getDeviceId();
        }

        return row1;
    }

    void getreportdatas(     List<FactArea> areaList, List<Map<String,Object>> phaseHis,String type, Map<String,Object> lastdata) throws ParseException {
        Map<String,Object>  itemdata;
        Map<String,Object>  itemdata1;
        Map<String,Object>  alldata=new HashMap<>();
        Float itemValue=null;
        Map<String,Object>  item=null;
        for(int i=0;i<phaseHis.size();i++){
            itemdata=phaseHis.get(i);
            itemdata1=new HashMap<>();
            itemdata1.putAll(phaseHis.get(i));
            if(type.equals("week")){
                itemdata.put("time","星期" + number2chinese(new Integer(itemdata.get("product").toString())) ) ;
            }else{
                itemdata.put("time",itemdata.get("product")+ (type.equals("date")?"时":type.equals("quarter")||type.equals("year")?"月":"日")) ;
            }

                Integer areaId=null;
                for(int j=0;j<areaList.size();j++){

                    areaId=areaList.get(j).getAreaId();
                    itemdata.put("valuea"+areaId,subtract(lastdata.get("valuea"+areaId),itemdata.get("valuea"+areaId)));
                    itemdata.put("valueb"+areaId,subtract(lastdata.get("valueb"+areaId),itemdata.get("valueb"+areaId)));
                    itemdata.put("valuec"+areaId,subtract(lastdata.get("valuec"+areaId),itemdata.get("valuec"+areaId)));

                    if (i==0){
                        alldata.put("time","合计");
                        alldata.put("valuea"+areaId,itemdata.get("valuea"+areaId));
                        alldata.put("valueb"+areaId,itemdata.get("valueb"+areaId));
                        alldata.put("valuec"+areaId,itemdata.get("valuec"+areaId));
                    }else{
                        alldata.put("valuea"+areaId, add(alldata.get("valuea"+areaId), itemdata.get("valuea"+areaId)));
                        alldata.put("valueb"+areaId, add(alldata.get("valueb"+areaId), itemdata.get("valueb"+areaId)));
                        alldata.put("valuec"+areaId, add(alldata.get("valuec"+areaId), itemdata.get("valuec"+areaId)));
                    }
               }

            lastdata=itemdata1;

        }

        phaseHis.add(alldata);
    }


    void getreport1datas(List<FactDevice> deviceList, List<Map<String,Object>> phaseHis,String type, Map<String,Object> lastdata) throws ParseException {
        Map<String,Object>  itemdata;
        Map<String,Object>  itemdata1;
        Map<String,Object>  alldata=new HashMap<>();
        lastdata=lastdata==null?new HashMap<>():lastdata;

        Float itemValue=null;
        Map<String,Object>  item=null;
        for(int i=0;i<phaseHis.size();i++){
            itemdata1=new HashMap<>();
            itemdata1.putAll(phaseHis.get(i));
            itemdata=phaseHis.get(i);
            if(type.equals("week")){
                itemdata.put("time","星期" + number2chinese(new Integer(itemdata.get("product").toString())) ) ;
            }else{
                itemdata.put("time",itemdata.get("product")+ (type.equals("date")?"时":type.equals("quarter")||type.equals("year")?"月":"日")) ;
            }

          Integer deviceId=null;
            for(int j=0;j<deviceList.size();j++){
                deviceId=deviceList.get(j).getDeviceId();
                itemdata.put("valuea"+deviceId,subtract(lastdata.get("valuea"+deviceId),itemdata.get("valuea"+deviceId)));
                itemdata.put("valueb"+deviceId,subtract(lastdata.get("valueb"+deviceId),itemdata.get("valueb"+deviceId)));
                itemdata.put("valuec"+deviceId,subtract(lastdata.get("valuec"+deviceId),itemdata.get("valuec"+deviceId)));
                if (i==0){
                    alldata.put("time","合计");
                    alldata.put("valuea"+deviceId,itemdata.get("valuea"+deviceId));
                    alldata.put("valueb"+deviceId,itemdata.get("valueb"+deviceId));
                    alldata.put("valuec"+deviceId,itemdata.get("valuec"+deviceId));
                }else{
                    alldata.put("valuea"+deviceId, add(alldata.get("valuea"+deviceId), itemdata.get("valuea"+deviceId)));
                    alldata.put("valueb"+deviceId, add(alldata.get("valueb"+deviceId), itemdata.get("valueb"+deviceId)));
                    alldata.put("valuec"+deviceId, add(alldata.get("valuec"+deviceId), itemdata.get("valuec"+deviceId)));
                }


           }


            lastdata=itemdata1;

        }
        phaseHis.add(alldata);

    }

    public static String number2chinese(int src) {
         String num[] = { "零","一", "二", "三", "四", "五", "六", "日", "八", "九"};
          return  num[src];
    }



    private String getLastWhere(String date) {

        if(date==null||date.equals("")){
            date=DateUtil.sdf5.format(new Date());
        }
        String datas=   DateUtil.addInteger(date,5,-1);
        String  where="  acquisition_time  like '"+datas+" 23%'";

        return  where;
    }




    private String getReportWhere(String type,String date) {
        String where="   ";
        if(date==null||date.equals("")){
            where="  acquisition_time >=CURDATE()";
        }else if(type.equals("date")){
            where="  acquisition_time  like '"+date+"%'";
        }else if(type.equals("week")){
            where="  WEEKOFYEAR(acquisition_time)=WEEKOFYEAR('"+date+"')  and acquisition_time>='"+date+"'" ;
        }else if(type.equals("month")){
            where="  month(acquisition_time)=month('"+date+"') and acquisition_time>='"+date+"'" ;
        }else if(type.equals("year")){
            where="  year(acquisition_time)=year('"+date+"') and acquisition_time>='"+date+"'" ;
        }else{
            where="  QUARTER(acquisition_time)=QUARTER('"+date+"') and acquisition_time>='"+date+"'" ;
         }
        return  where;
    }



    private String getDatasection(String type,String date) throws ParseException {
        String where="   ";
        String endDay="";
        if(type.equals("week")){
             endDay=    DateUtil.getLastDaysByW(date);
        }else if(type.equals("month")){
              endDay=    DateUtil.getLastDaysByM(date);
        }else if(type.equals("year")){
            endDay=    DateUtil.getLastDaysByY(date);
        }else   if(type.equals("quarter")){
            endDay=    DateUtil.getLastDaysByQ(date);
        }else{
            return "";
        }
        return  date+"到"+endDay;
    }




    private String getReportWhere1(String type,String date) throws ParseException {
	    Date indate=DateUtil.sdf5.parse(date);
	    Date now=new Date();
	   String where=" a.help_keyword_id < 24";
       if(type.equals("week")){
           where="  a.help_keyword_id > 0 and  a.help_keyword_id < 8";
        }else if(type.equals("month")){
           where="  a.help_keyword_id  > 0 and  a.help_keyword_id <=day(last_day('"+date+"'))";
        }else if(type.equals("quarter")){
            Integer quarterByDate=  DateUtil.getQuarterStartByDate(date);
            where="  a.help_keyword_id  >= "+quarterByDate+" and  a.help_keyword_id < "+  (quarterByDate+3) +"";
        }else if(type.equals("year")){
           Integer year=now.getYear();
           where="  a.help_keyword_id  >= 1 and  a.help_keyword_id <= "+(  indate.getYear()==now.getYear()?now.getMonth()+1:12);
       }
        return  where;
    }




    //数据相加
    private Object add(Object object1,Object object2){
        DecimalFormat b = new DecimalFormat("0.00");
        object1=object1==null?0:object1;
        object2=object2==null?0:object2;


        Float data2=new Float(object2.toString());
        Float data1=new Float(object1.toString());
        return b.format(data2+data1);
    }

    //数据相减
    private Object subtract(Object object1,Object object2){
        DecimalFormat b = new DecimalFormat("0.00");
        if(object1==null||new Float(object1.toString())==0){
            return b.format(object2);
        }

        if(object2!=null){
            Float data2=new Float(object2.toString());
            Float data1=new Float(object1.toString());
            if(data2>data1){

                return b.format(data2- data1);
            }
        }
        return b.format(0);
    }

    //数据相减
    private Object subtract1(Object object1,Object object2){
        if(object1==null){
            object1=0.00;
        }
        if(object2==null){
            object2=0.00;
        }

        Float data2=new Float(object2.toString());
        Float data1=new Float(object1.toString());
        DecimalFormat b = new DecimalFormat("0.00");
        return b.format(data2- data1);

    }


    private Object  formatGrowthrate(Object object1,Object object2){
        if(object1==null){
            object1=0;
        }
        if(object2==null){
            object2=0;
        }
        Float data2=new Float(object2.toString());
        Float data1=new Float(object1.toString());
        if(data1==0.0&&data1==0.0){
            return  "--";
        }
        if(data1==0.0&&data2>0){
          return "100%";
        }else  if(data1>0&&data2==0.0){
            return "-100%";
        }


        return ((data2-data1)/data2)*100+"%";

    }



	private void getChartData(LocalDateTime time,String[] phaseTime ,Float[] yestodayNum , Map<String,Float> phaseHisMap,Map<String,Object> returnDate,String title){
        Float maxValue=null;
        String maxTime=null;
        Float cValue=null;
        String timeItem=null;

        Float lastValue=new Float(0);
        LocalDateTime lasttime = time.plusMinutes(-30);
        timeItem=lasttime.format(DateUtil.formatter);
        cValue=phaseHisMap.get(timeItem);
        if(cValue!=null){
            lastValue=new Float(cValue);
        }

        for(int i=0;i<48;i++){
            timeItem=time.format(DateUtil.formatter);
            cValue=phaseHisMap.get(timeItem);
            phaseTime[i]=time.format(DateUtil.formatter1);
            if(cValue==null){
                yestodayNum[i]=new Float(0);
            }else {
                yestodayNum[i]=cValue-lastValue;
                if( yestodayNum[i]>0){
                    lastValue=cValue;
                }else{
                    yestodayNum[i]=new Float(0);
                }
                if(maxValue==null){
                    maxValue= yestodayNum[i];
                    maxTime= timeItem;
                }else if ( yestodayNum[i]>maxValue){
                    maxValue=yestodayNum[i];
                    maxTime= timeItem;
                }
            }
            time = time.plusMinutes(30);
        }
        returnDate.put(title+"Max",maxValue);
        returnDate.put(title+"MaxTime",maxTime);

    }

	public void findAlarmAnalysisByType(Integer typeId,Map<String,Object> returnDate,String where) {
        List<Map<String,Object>> phaseTrend=runningDataService.energyTrendStatistics(where,typeId);
		Object[] trendTime=new Object[phaseTrend.size()];
		Object[] trendData=new Object[phaseTrend.size()];
		Object lastNum= 0;
        Map<String,Object> energyNum= ( Map<String,Object>)CacheUtil.getObject("energyNum");
        if(energyNum==null){
            energyNum =runningDataService.getEnergyNumStatistics(where);
        }
        if(typeId==1){
            lastNum= energyNum.get("yestoday_num");
        }else  if(typeId==2){
            lastNum= energyNum.get("last_mouth_num");
        }else{
            lastNum= energyNum.get("last_year_num");
        }
System.out.println(lastNum);
        Object timeItem=null;
		for(int  i=0;i<phaseTrend.size();i++){
			trendTime[i]=phaseTrend.get(i).get("product");
            timeItem=phaseTrend.get(i).get("value");
            System.out.println(timeItem);
            Float  data=new Float(timeItem.toString())-new Float(lastNum.toString());

            if( data>0){
                trendData[i]=data;
                lastNum=timeItem;
            }else{  trendData[i]=0;}


		}
        returnDate.put("trendTime",trendTime);
        returnDate.put("trendData",trendData);

	}



    private String getWhere(Integer deviceId,Integer areaId){
        String where="  1=1 ";
        if(deviceId!=null){
            where+=" and device_id="+deviceId;
        }
        if(areaId!=null){
            where+="  and  device_id in ( select device_id  from fact_device where  FIND_IN_SET(area_id,fun_get_area_chindids("+areaId+")))";
        }
        return  where;
    }
}
